﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace QuickStart
{
	public class MemoryCustomerRepository : ICustomerRepository
	{
		public Dictionary<string, Customer> Entities { get; private set; }

		public MemoryCustomerRepository()
		{
			Entities = new Dictionary<string, Customer>();
		}

		public string Create(Customer entity)
		{
			entity.Id = Guid.NewGuid().ToString();
			Entities[entity.Id] = entity;
			return entity.Id;
		}

		public bool Update(Customer entity)
		{
			if (!Entities.ContainsKey(entity.Id))
				return false;

			Entities[entity.Id] = entity;
			return true;
		}

		public bool Delete(Customer entity)
		{
			return Delete(entity.Id);
		}

		public bool Delete(string entityId)
		{
			return Entities.Remove(entityId);			
		}

		public Customer Get(string entityId)
		{
			Customer entity = default(Customer);
			Entities.TryGetValue(entityId, out entity);
			return entity;
		}

		public IEnumerable<Customer> GetAll()
		{
			return Entities.Values;
		}

		public IEnumerable<Customer> FindByName(string criteria)
		{
			return from c in Entities.Values
					 where
						c.FirstName.IndexOf(criteria, StringComparison.CurrentCultureIgnoreCase) != -1 ||
						c.LastName.IndexOf(criteria, StringComparison.CurrentCultureIgnoreCase) != -1 
					 select c;
		}
	}
}
